package com.xiaochong.bitong.api.service;

import com.alibaba.fastjson.JSON;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.component.RedisCacheComponent;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.utils.ListSortUtil;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.mapper.ExchangeTransactionpairMiddleMapper;
import com.xiaochong.tir.common.data.mapper.SelfSelectedMapper;
import com.xiaochong.tir.common.data.mapper.SelfSelectedSortMapper;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.data.po.ExchangeTransactionpairMiddle;
import com.xiaochong.tir.common.data.po.SelfSelected;
import com.xiaochong.tir.common.data.po.SelfSelectedSort;
import com.xiaochong.tir.common.data.redisPo.CoinPriceVo;
import com.xiaochong.tir.common.data.vo.ApiKActionQuantizationVo;
import com.xiaochong.tir.common.data.vo.ApiResultVo;
import com.xiaochong.tir.common.data.vo.BtUser;
import com.xiaochong.tir.common.data.vo.app.AppSelfSelectCoinPairVo;
import com.xiaochong.tir.common.util.ApiResultCodeUtils;
import com.xiaochong.tir.common.util.RedisKeyApp;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: java类作用描述
 * @Author: org
 * @CreateDate: 2018/8/15 18:12
 */
@Service
public class SelfSelectService {

    @Autowired
    private SelfSelectedMapper selfSelectedMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SelfSelectedSortMapper selfSelectedSortMapper;
    @Autowired
    private RedisCacheComponent redisCacheComponent;
    @Autowired
    private ExchangeTransactionpairMiddleMapper exchangeTransactionpairMiddleMapper;
    @Autowired
    private RedisServer redisServer;

    /**
     * 货币、交易对新增、删除、置顶（修改）
     * @param type
     * @param token
     * @param unique_annotation
     * @param flagType
     * @return
     */
    public ApiResultVo joinAndCancelShelSelect(Integer type, String token, Integer unique_annotation, Integer flagType) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(null == type || null == unique_annotation || null == flagType){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            BtUser btUser = commonService.getUserByToken(token);
            Integer user_id ;
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            user_id = btUser.getId();
            LogTrace.infoKvs("加入自选","type",type.toString(),"user_id",user_id.toString(),"unique_annotation",unique_annotation.toString(),"flagType",flagType.toString());
            SelfSelected selfSelected = new SelfSelected();
            selfSelected.setType(type.toString());
            selfSelected.setUniqueAnnotation(unique_annotation);
            selfSelected.setUserId(user_id);
            int deleteOrInsertInt = 0;
            if(1 == flagType){
                //验证是否已经存在
                List<SelfSelected> list = selfSelectedMapper.selectByEntityList(selfSelected);
                if(list == null || list.size() == 0){
                    selfSelected.setCreateTime(new Date());
                    //deleteOrInsertInt = selfSelectedMapper.insert(selfSelected);
                    deleteOrInsertInt = selfSelectedMapper.insertReturnId(selfSelected);
                    if(selfSelected.getId() != null && deleteOrInsertInt == 1){
                        Map<String,Object> params = new HashMap();
                        params.put("type",1);
                        params.put("userId",user_id);
                        params.put("sort",selfSelected.getId()+",");
                        int congInt = 0;
                        congInt =selfSelectedSortMapper.updateByInsertOrDelete(params);
                        if(congInt == 0){
                            SelfSelectedSort selfSelectedSort = new SelfSelectedSort();
                            selfSelectedSort.setSort(selfSelected.getId()+",");
                            selfSelectedSort.setUserId(user_id);
                            deleteOrInsertInt = selfSelectedSortMapper.insert(selfSelectedSort);
                        }
                    }
                }
            }else if(2 == flagType){
                selfSelected = selfSelectedMapper.selectByEntity(selfSelected);//查询id
                if(selfSelected.getId() != null){
                    deleteOrInsertInt = selfSelectedMapper.deleteByEntity(selfSelected);
                    if(deleteOrInsertInt == 1){
                        Map<String,Object> params = new HashMap();
                        params.put("type",2);
                        params.put("userId",user_id);
                        params.put("sort",selfSelected.getId()+",");
                        selfSelectedSortMapper.updateByInsertOrDelete(params);
                    }
                }
                //deleteOrInsertInt = selfSelectedMapper.deleteByPrimaryKey(selfSelected.getId());
            }else{
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("flagType参数错误");
                return resultVo;
            }
            //判断是否插入/删除成功
            if(deleteOrInsertInt > 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("加入自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }

    public ApiResultVo updateShelSelect(Integer selectId, String token) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(null == selectId){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            BtUser btUser = commonService.getUserByToken(token);
            Integer user_id ;
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            user_id = btUser.getId();
            LogTrace.infoKvs("置顶自选","selectId",selectId.toString(),"user_id",user_id.toString());
            SelfSelected selfSelected = new SelfSelected();
            selfSelected.setId(selectId);
            selfSelected.setCreateTime(new Date());
            int deleteOrInsertInt = 0;

            deleteOrInsertInt = selfSelectedMapper.updateByPrimaryKey(selfSelected);
            //判断是否插入/删除成功
            if(deleteOrInsertInt > 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("置顶自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }

    public ApiResultVo updateSelfSelectSort(String sort, String token) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(StringUtils.isBlank(sort)){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            BtUser btUser = commonService.getUserByToken(token);
            Integer user_id ;
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            SelfSelectedSort selfSelectedSort  = new SelfSelectedSort();
            user_id = btUser.getId();
            LogTrace.infoKvs("置顶排序自选","sort",sort,"user_id",user_id.toString());
            if(!sort.endsWith(",")){
                sort = sort+",";
            }
            selfSelectedSort.setSort(sort);
            selfSelectedSort.setUserId(user_id);
            int deleteOrInsertInt = 0;
            deleteOrInsertInt = selfSelectedSortMapper.updateByUserId(selfSelectedSort);
            //判断是否插入/删除成功
            if(deleteOrInsertInt > 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("更新失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("置顶排序自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }

    /**
     * byid删除
     * @param selectId
     * @param token
     * @return
     */
    public ApiResultVo deleteShelSelect(Integer selectId, String token) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(null == selectId){//PARAMS_ERROR
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("参数错误");
                return resultVo;
            }
            BtUser btUser = commonService.getUserByToken(token);
            Integer user_id ;
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            user_id = btUser.getId();
            LogTrace.infoKvs("加入自选","selectId",selectId.toString(),"user_id",user_id.toString());
            /*SelfSelected selfSelected = new SelfSelected();
            selfSelected.setId(selectId);*/
            int deleteInt = 0;
            deleteInt = selfSelectedMapper.deleteByPrimaryKeyNew(selectId);
            if(deleteInt > 0){
                Map<String,Object> params = new HashMap();
                params.put("type",2);
                params.put("userId",user_id);
                params.put("sort",selectId+",");
                selfSelectedSortMapper.updateByInsertOrDelete(params);
            }
            //判断是否插入/删除成功
            if(deleteInt > 0){
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setMessage("成功");
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("加入自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }

    public ApiResultVo coinPairMarketList(Integer pageIndex, Integer pageSize, String token, String sortField, String sortType) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        List<AppSelfSelectCoinPairVo> resultList = new ArrayList<>();
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            AppSelfSelectCoinPairVo temResult;
            BtUser btUser = commonService.getUserByToken(token);
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
           /* btUser = new BtUser();
            btUser.setId(45);*/
            SelfSelectedSort selfSelectedSort = new SelfSelectedSort();
            selfSelectedSort.setUserId(btUser.getId());
            selfSelectedSort = selfSelectedSortMapper.selectByEntity(selfSelectedSort);
            List<SelfSelected> selecteds = new ArrayList<>();
            SelfSelected selected = new SelfSelected();
            if(selfSelectedSort.getId()!=null && StringUtils.isNotBlank(selfSelectedSort.getSort())){
                String[] sort = selfSelectedSort.getSort().split(",");
                if(sort.length > 0){
                    for(int i =0;i<sort.length;i++){
                        Integer id = Integer.valueOf(String.valueOf(sort[i]));
                        if(id != null){
                            selected.setId(id);
                            SelfSelected ss = selfSelectedMapper.selectByEntity(selected);
                            if(ss != null){
                                selecteds.add(ss);
                            }
                        }
                    }
                }
            }
            List<CurrencyInfo> CurrencyInfoList = redisCacheComponent.getCurrencyList();
            Map<Integer,CurrencyInfo> currencyInfoMap = new HashMap<>();
            CurrencyInfo currencytemp;
            for(CurrencyInfo currencyInfo : CurrencyInfoList) {
                currencyInfoMap.put(currencyInfo.getId(),currencyInfo);
            }
            if(selecteds.size() > 0){
                List<Integer> exchangeMiddle = new ArrayList<>();
                for(SelfSelected sd : selecteds){
                    String type = sd.getType();
                    if("1".equals(type)){//交易对
                        ExchangeTransactionpairMiddle middle = new ExchangeTransactionpairMiddle();
                        middle.setId(sd.getUniqueAnnotation());//selectByEntity
                        middle  = exchangeTransactionpairMiddleMapper.selectByEntity(middle);
                        if(middle == null || StringUtils.isBlank(middle.getTransactionName()) || null == middle.getExchangeId()){
                            continue;
                        }
                        String data = redisServer.get(RedisKeysUtils.K_ACTION_SELF_SELECT+"@"+middle.getExchangeId()+"@"+middle.getTransactionName());
                        if(StringUtils.isNotBlank(data)){
                            ApiKActionQuantizationVo k = JSON.parseObject(data,ApiKActionQuantizationVo.class);
                            if(k != null){
                                temResult = new AppSelfSelectCoinPairVo();
                                temResult.setType(1);
                                temResult.setAmount24h(k.getAmount().toString());
                                temResult.setChange24hDouble(k.getChangePrice());
                                temResult.setChange24h(k.getChangePrice().toString());
                                temResult.setChangeFlag(k.getChangFlag().toString());
                                temResult.setCoinOrPairName(k.getTransactionName());
                                temResult.setExchangeId(middle.getExchangeId());
                                temResult.setExchangeName(k.getExchangeName());
                                temResult.setPairId(middle.getTransactionId());
                                temResult.setPriceCnyDouble(k.getLastOpenPrice());
                                temResult.setPriceCny(k.getLastOpenPrice().toString());
                                temResult.setPriceUsd(k.getLastOpenPriceUsd().toString());
                                temResult.setMiddleId(middle.getId());
                                temResult.setSelectId(sd.getId());
                                resultList.add(temResult);
                            }
                        }
                    }else if("2".equals(type)){//货币
                        currencytemp = currencyInfoMap.get(sd.getUniqueAnnotation());
                        if(currencytemp != null){
                            String priceRedisKey = RedisKeyApp.COIN_PRICE+currencytemp.getCmcId();
                            temResult = new AppSelfSelectCoinPairVo();
                            String priceRedisData = redisServer.get(priceRedisKey);
                            if(StringUtils.isNotBlank(priceRedisData)){
                                CoinPriceVo coinPriceVo = JSON.parseObject(priceRedisData,CoinPriceVo.class);
                                if(coinPriceVo!=null){
                                    temResult.setType(2);
                                    temResult.setAmount24h(coinPriceVo.getAmount24H());
                                    temResult.setChange24h(coinPriceVo.getChang24h());
                                    temResult.setChange24hDouble(Double.valueOf(coinPriceVo.getChang24h()));
                                    temResult.setChangeFlag(coinPriceVo.getChang());
                                    temResult.setCoinOrPairName(currencytemp.getSymbol());
                                    temResult.setPriceCnyDouble(Double.valueOf(coinPriceVo.getPriceCny()));
                                    temResult.setPriceCny(coinPriceVo.getPriceCny());
                                    temResult.setPriceUsd(coinPriceVo.getPriceUsd());
                                    temResult.setMiddleId(currencytemp.getId());
                                    temResult.setCoinNameCn(currencytemp.getCoinNameCn());
                                    temResult.setCmcId(currencytemp.getCmcId());
                                    temResult.setSelectId(sd.getId());
                                    resultList.add(temResult);
                                }
                            }
                        }
                    }
                }
            }
            //判断是否排序
            if(StringUtils.isNotBlank(sortField)){
                if(StringUtils.isBlank(sortType)){
                    sortType = "desc";
                }
                if( !"asc".equals(sortType) && !"desc".equals(sortType)){
                    sortType = "desc";
                }
                if("change24hDouble".equals(sortField) || "priceCnyDouble".equals(sortField)){
                    ListSortUtil util=new ListSortUtil();
                    util.mySort( resultList, sortField.trim(), sortType.trim() );
                }
            }

            if(resultList.size() > 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
                resultVo.setData(resultList);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("无自选");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("置顶排序自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;

    }

    public ApiResultVo coinPairNoMarketList(String token) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            BtUser btUser = commonService.getUserByToken(token);
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            SelfSelectedSort selfSelectedSort = new SelfSelectedSort();
            selfSelectedSort.setUserId(btUser.getId());
            if(selfSelectedSort.getId()!=null){

            }
            //判断是否插入/删除成功
            if(5> 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("更新失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("置顶排序自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }

    /**
     * 批量删除
     * @param token
     * @param selectIds
     * @return
     */
    public ApiResultVo deleteShelSelectBatch(String token, String selectIds) {
        ApiResultVo resultVo = new ApiResultVo();
        resultVo.setDataStamp(System.currentTimeMillis());
        resultVo.setTradeId(LogTrace.getTrace().getTraceId());
        try {
            if(StringUtils.isBlank(selectIds)){
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("selectIds参数错误");
                return resultVo;
            }
            BtUser btUser = commonService.getUserByToken(token);
            if(btUser == null || btUser.getId() == null){
                resultVo.setCode(ReturnCode.TOKEN_LOSE);
                resultVo.setMessage("Token异常或失效");
                return resultVo;
            }
            //批量删除
            if(selectIds.endsWith(",")){
                selectIds = selectIds.substring(0,selectIds.length()-1);
            }
            String[] selectArray = selectIds.split(",");
            if (selectArray ==null || selectArray.length == 0){
                resultVo.setCode(ReturnCode.PARAMS_ERROR);
                resultVo.setMessage("没有可删除的数据");
                return resultVo;
            }
            LogTrace.infoKvs("批量删除自选","token",token,"selectIds",selectIds,"user_id",String.valueOf(btUser.getId()));
            List<String> deleteIdStr = Arrays.asList( selectArray);
            List<Integer> deleteId = new ArrayList<>();
            for(String str : deleteIdStr){
                deleteId.add(Integer.valueOf(str));
            }
            int successCount = selfSelectedMapper.deleteBatch(deleteId);
            if(successCount > 0){//删除排序
                for(Integer id : deleteId){
                    Map<String,Object> params = new HashMap();
                    params.put("type",2);
                    params.put("userId",btUser.getId());
                    params.put("sort",id+",");
                    selfSelectedSortMapper.updateByInsertOrDelete(params);
                }
            }
            //判断是否插入/删除成功
            if(successCount > 0){
                resultVo.setMessage("成功");
                resultVo.setCode(ReturnCode.SUCCESS);
            }else{
                resultVo.setCode(ReturnCode.DATA_NOT_EXIST);
                resultVo.setMessage("更新失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error("批量删除自选error",e);
            resultVo.setCode(ReturnCode.ERROR);
            resultVo.setMessage("系统错误");
        }
        return resultVo;
    }
}
